﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_TOOL.Tool.UserControls;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_TOOL.Tool.Forms
{
    public partial class frm_JustNewAdd : DevExpress.XtraEditors.XtraForm
    {
        private DataTable dt = new DataTable();
        private ucJustNew parent;
        private ucImport parentImport;
        private bool firstLoadFromImport = true;
        public string ToolId;
        public bool FromImport;
        public int import;
        private bool dropDown;
        private DataTable dataTable;
        AutoCompleteStringCollection itemToolID = new AutoCompleteStringCollection();
        private LogUtils log;

        public frm_JustNewAdd(ucJustNew fJustNew=null, ucImport fImport = null, bool isFromImport = false)
        {
            InitializeComponent();
            btTAdd.Image = ERP_RORZE_TOOL.Properties.Resources.add;
            btTCancel.Image = ERP_RORZE_TOOL.Properties.Resources.cancel;
            parent = fJustNew;
            parentImport = fImport;
            FromImport = isFromImport;
            //this.CancelButton = this.btTCancel;
            cmbToolID.LostFocus += cmbToolID_LostFocus;
            this.ActiveControl = cmbToolID;
            log = new LogUtils();

        }

        void cmbToolID_LostFocus(object sender, EventArgs e)
        {
            if (cmbToolID.Items.Count <= 0)
            {
                foreach (string s in cmbToolID.AutoCompleteCustomSource)
                {
                    if (cmbToolID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbToolID.Text = s;
                        break;
                    }
                }

            }

        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            if (FromImport)
            {
                dtpTDate.Value = DateTime.Today;
                BindDataFromImport();
                firstLoadFromImport = false;
            }
            else
            {
                dtpTDate.Value = DateTime.Today;
                BindDataTool();
            }
        }

        private void btTAdd_Click_1(object sender, EventArgs e)
        {
            AddTool();
        }

        private void btTCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cmbToolID_SelectedIndexChanged(object sender, EventArgs e)
        {
            //if (!cmbToolID.Text.Equals(string.Empty) && !FromImport)
            //{
            //    import = CheckInput();
            //    MessageBox.Show(string.Format(ToolConstants.Message.JustNew.ImportQuantity, cmbToolID.Text, import.ToString()), ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            //else if (!cmbToolID.Text.Equals(string.Empty) && FromImport && !firstLoadFromImport)
            //{
            //    import = CheckInput();
            //    MessageBox.Show(string.Format(ToolConstants.Message.JustNew.ImportQuantity, cmbToolID.Text, import.ToString()), ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK, MessageBoxIcon.Information);

            //}
            
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void cmbToolID_DropDown(object sender, EventArgs e)
        {
            dropDown = true;

            System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox;
            combo.AutoCompleteMode = AutoCompleteMode.None;
            if (combo.Items.Count <= 0)
            {
                Cursor.Current = Cursors.WaitCursor;
                switch (combo.Name)
                {
                    case "cmbToolID":
                        foreach (var item in itemToolID)
                        {
                            cmbToolID.Items.Add(item.ToString());

                        }
                        break;

                }
                Cursor.Current = Cursors.Default;


            }
        }

        private void frm_JustNewAdd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    btTAdd.Focus();
                    this.btTAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btTAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dtpTDate.Focus();
            }
        }

        #region Private methods

        private bool GetDataTool(JustNew o)
        {
            #region Check valid

            DataTable dtCheck;

            if (Utilities.IsNullOrEmpty(dtpTDate.Value.ToString()))
            {
                MessageBox.Show(ToolConstants.Message.JustNew.DateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbToolID.Text))
            {
                MessageBox.Show(ToolConstants.Message.JustNew.ToolIDCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Tool] where [ToolID]=N'" + cmbToolID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.JustNew.ToolIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbToolID.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtTQuantity.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.JustNew.QuantityCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (int.Parse(txtTQuantity.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.JustNew.QuantityMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtTQuantity.Focus();
                return false;

            }

            if (int.Parse(txtTQuantity.Text) > 0)
            {
                string fieldName = ToolConstants.StoreProcedure.FieldName.DaoMoi;
                string where = ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
                string storedName = ToolConstants.StoreProcedure.FTonKhoTongHop;

                int import = Utilities.CheckInput(fieldName, storedName, where);

                if (import < int.Parse(txtTQuantity.Text))
                {
                    MessageBox.Show(string.Format(ToolConstants.Message.JustNew.WrongQuantity, cmbToolID.Text, import.ToString(), txtTQuantity.Text), ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtTQuantity.Text = "";
                    txtTQuantity.Focus();
                    return false;

                }

            }
            #endregion

            o.Date = dtpTDate.Value.Date;
            o.ToolID = cmbToolID.Text.ToString();
            o.Quantity = int.Parse(txtTQuantity.Text);
            o.Note = memoTNote.Text;

            return true;
        }

        private void BindDataTool()
        {
            ToolHelper helper = new ToolHelper(new Tools());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemToolID.Add(row[ToolConstants.Entities.Tool.FieldName.ToolID].ToString());

            }
            cmbToolID.AutoCompleteCustomSource = itemToolID;

            if (!FromImport)
            {
                cmbToolID.Text = ToolId;
            }
        }

        private void AddTool()
        {
            JustNewHelper helper = new JustNewHelper(new JustNew());
            if (GetDataTool(helper.ValueObject))
            {
                if (helper.Insert() > 0)
                {

                    //write Log
                    log.Table = LogConstant.Table.ToolCutting.JustNew;
                    log.Task = LogConstant.Task.Insert;
                    log.Description = helper.ValueObject.ToolID;
                    log.WriteLog();

                    if (Utilities.MessageConfirmationYesNo(ToolConstants.Message.AddSuccessAndQuestion))
                    {

                        dtpTDate.Value = DateTime.Now;
                        cmbToolID.Text = string.Empty;
                        txtTQuantity.Text = string.Empty;
                        memoTNote.Text = string.Empty;
                        //lblStatus.Visible = false;
                        cmbToolID.Focus();
                    }
                    else
                    {
                        this.Close();
                    }
                }
                else
                {

                    Utilities.MessageErrorOk(ToolConstants.Message.AddFailed);
                }
                if (parent!=null)
                {
                    parent._action = 0;
                    parent.BindDatatoGrid();
                }
                if (FromImport)
                {
                    parentImport.BindDatatoGridJustNew();
                }

            }
        }

        private void BindDataFromImport()
        {
            BindDataTool();

            cmbToolID.Text = ToolId;
            //if (cmbToolID.Text == null)
            //{
            //    cmbToolID.Text = cmbToolID.Items[0];
            //}
            //import = CheckInput();
            //lblStatus.Visible = true;
            //lblStatus.Text = string.Format(ToolConstants.Message.JustNew.ImportQuantity, cmbToolID.Text,
            //                               import.ToString());

        }

        private int CheckInput()
        {
            string fieldName = ToolConstants.StoreProcedure.FieldName.DaoMoi;
            string where = ToolConstants.StoreProcedure.FieldName.ToolID + "='" + cmbToolID.Text + "'";
            string storedName = ToolConstants.StoreProcedure.FTonKhoTongHop;

            return Utilities.CheckInput(fieldName, storedName, where);

        }

        #endregion

        private void cmbToolID_DropDownClosed(object sender, EventArgs e)
        {
            dropDown = false;
            ((System.Windows.Forms.ComboBox)sender).AutoCompleteMode = AutoCompleteMode.Append;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Add controls for which Arrow keys => focus is not required.
            if ((!dropDown && (ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox || ActiveControl is System.Windows.Forms.DateTimePicker)))
            {
                switch (keyData)
                {
                    case Keys.Up:
                    case Keys.Down:

                        bool forward = (keyData == Keys.Down);
                        if (this.ProcessTabKey(forward))
                        {
                            return true;
                        }

                        break;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cmbToolID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {

                string sql = "SELECT * FROM  [333_Tool]" +
                             "WHERE [333_Tool].ToolID = N'" + cmbToolID.Text + "';";
                dataTable = BaseDAO.ExecuteQuery(sql);
                if (dataTable.Rows.Count > 0)
                {
                    txtToolName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolName].ToString();
                }
                else
                {
                    txtToolName.Text = string.Empty;
                }

                //////////////////
                //if (cmbToolID.Items.Count <= 0)
                //{
                    if (!cmbToolID.Text.Equals(string.Empty) && !FromImport)
                    {
                        import = CheckInput();
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.JustNew.ImportQuantity, cmbToolID.Text, import.ToString()),
                            ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (!cmbToolID.Text.Equals(string.Empty) && FromImport && !firstLoadFromImport)
                    {
                        import = CheckInput();
                        MessageBox.Show(
                            string.Format(ToolConstants.Message.JustNew.ImportQuantity, cmbToolID.Text, import.ToString()),
                            ToolConstants.Form.MessageBox.Message, MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                //}
            }
        }

        
    }
}